<template>
  <div class="body-wrapper">
    <div class="body-top">
      <!-- 查询 -->
      <span class="select">
        <h4>来源机构:</h4>
        <a-select ref="select" v-model:value="selectstandardSourceValue" style="width: 120px">
          <a-select-option v-for="(item, num) in sources" :key="num" :value="item">{{ item }}</a-select-option>
        </a-select>
      </span>
      <span class="select">
        <h4>标准状态:</h4>
        <a-select ref="select" v-model:value="selectstandardStatusValue" :options="options" style="width: 120px"> </a-select>
      </span>
      <span class="select">
        <h4>标准编号:</h4>
        <a-input v-model:value="inputstandardIdValue" placeholder="请输入标准编号" />
      </span>
      <span class="select">
        <h4>中文名称:</h4>
        <a-input v-model:value="inputstandardNameValue" placeholder="请输入中文名称" />
      </span>
      <span class="select">
        <h4>英文名称:</h4>
        <a-input v-model:value="inputstandardEnglishValue" placeholder="请输入英文名称" />
      </span>
      <a-button @click="reset">重置</a-button>
      <a-button type="primary" @click="search">查询</a-button>
      <br />

      <div class="body-top2">
        <a-button :disabled="activeClass1" :class="{ activeClass: !activeClass1, issue: true }" @click="allIssueAndPause(3, 2)">批量发布</a-button>&nbsp;
        <a-button style="margin-right: 700px" :disabled="activeClass2" :class="{ activeClass: !activeClass2, pause: true }" @click="allIssueAndPause(2, 3)">批量停用</a-button>
        <!-- 弹窗提示 -->
        <a-button id="btn-top" type="primary" @click="downloadFile">导入模板下载</a-button>
        <a-button id="btn-top" type="primary" @click="handleClickCodeIn">标准导入</a-button>
        <!-- 标准导入弹窗 -->
        <file-up v-model:visible="visibleCodeIn" action="http://10.255.70.21:2121/standard/uploadDataStandard" @change-show1="ChangeShow1"> </file-up>
        <!-- 新增码表弹窗 -->
        <a-button id="btn-top" type="primary" @click="showModal(dataSource)">新增标准</a-button>
        <addDatas
          :data-list="datas"
          :new-data="newData"
          :code-dialog-name="codeDialogName"
          :dialog-statue="dialogStatue"
          :add-code-table="addCodeTable"
          @change-show="showAddCodeDialog"
          @edit-successed="handleEditSuccessed"
        >
        </addDatas>
      </div> </div
    ><br />

    <!-- 表格 -->
    <div class="relative py-8">
      <a-table :data-source="dataSource" :pagination="pagination" :row-selection="{ selectedRowKeys: arr, onChange: selectChangEtion }" :row-key="(record: any) => { return record.standardId }">
        <a-table-column id="components-modal-demo-position" key="standardId" title="码表编号" :width="90" fixed="left">
          <template #default="{ column, record }">
            <template v-if="column.key === 'standardId'">
              <a @click="showSmallModal(record.standardId, record)"> {{ record.standardId }} </a>
            </template>
          </template>
        </a-table-column>

        <a-table-column key="standardName" data-index="standardName" :width="100">
          <template #title><span>中文名称</span></template>
        </a-table-column>
        <a-table-column key="standardDataType" data-index="standardDataType" :width="90">
          <template #title><span>数据类型</span></template>
          <template #default="{ record }">
            <span>
              {{ standardsStatus[record.standardStatus] }}
            </span>
          </template>
        </a-table-column>
        <a-table-column key="standardDataAccuracy" data-index="standardDataAccuracy" :width="90">
          <template #title><span>取值范围</span></template>
        </a-table-column>
        <a-table-column key="codesId" title="枚举范围" :width="100">
          <template #default="{ column, record }">
            <template v-if="column.key === 'codesId'">
              <a @click="showEnumModal(record.codesId)"> 企业类型码表 </a>
            </template>
          </template>
        </a-table-column>
        <a-table-column key="standardIsNull" data-index="码表状态" :width="90">
          <template #title><span>是否可为空</span></template>
          <template #default="{ record }">
            <span>
              <template v-if="record.standardIsNull == 1"> 不可为空 </template>
              <template v-else-if="record.standardIsNull == 2"> 可为空 </template>
            </span>
          </template>
        </a-table-column>
        <!-- <a-table-column key="standardIsNull" :width="90"
          >{{ nullData }}
          <template #title><span>是否可为空</span></template>
        </a-table-column> -->
        <a-table-column key="standardStatus" data-index="standardStatus" :width="90">
          <template #title><span>码表状态</span></template>
          <template #default="{ record }">
            <span>
              <a-tag :color="Colors[record.standardStatus]">{{ Status[record.standardStatus] }}</a-tag>
            </span>
          </template>
        </a-table-column>
        <a-table-column
          key="modifyTime"
          data-index="modifyTime"
          :width="180"
          :sorter="
            (a: DataItem, b: DataItem) => {
              return a.modifyTime > b.modifyTime ? 1 : -1;
            }
          "
        >
          <template #title><span>更新时间</span></template>
        </a-table-column>
        <a-table-column key="action" title="操作" :width="200" fixed="right">
          <template #default="{ record }">
            <span>
              <template v-if="record.standardStatus == 2">
                <a-popconfirm title="请确认是否停用该码表？" ok-text="是" cancel-text="否" @confirm="confirm3(record.standardId)">
                  <a-button class="operate" type="primary">停用</a-button></a-popconfirm
                >
              </template>
              <template v-else-if="record.standardStatus == 3">
                <a-popconfirm title="请确认是否发布该码表？" ok-text="是" cancel-text="否" @confirm="confirm2(record.standardId)">
                  <a-button class="operate" type="primary">发布</a-button></a-popconfirm
                >
                <a-button class="operate" type="primary" @click="showEditModal(record)">编辑</a-button>
              </template>
              <template v-else-if="record.standardStatus != 3">
                <a-popconfirm title="请确认是否发布该码表？" ok-text="是" cancel-text="否" @confirm="confirm2(record.standardId)">
                  <a-button class="operate" type="primary">发布</a-button>
                </a-popconfirm>
                <a-button class="operate" type="primary" @click="showEditModal(record)">编辑</a-button>

                <a-popconfirm v-if="dataSource.length" title="请确认是否删除该码表？" ok-text="是" cancel-text="否" @confirm="confirm1(record.standardId)">
                  <a-button class="operate" type="primary">删除</a-button></a-popconfirm
                >
              </template>
            </span>
          </template>
        </a-table-column>
      </a-table>
    </div>
  </div>
  <!-- 编码弹窗 -->
  <id-table v-model:visible="visibleIdModal" :small-modal-id1="smallModalId1" :data-table="dataTable" @change-show="ChangeShowId"></id-table>
  <!-- 枚举范围弹窗 -->
  <small-table :visible-small-modal="visibleSmallModal" :small-modal-id="smallModalId" @change-show="handleChangeShowSmallModal"></small-table>
</template>
<script setup lang="ts">
  import addDatas from './component/addDatas.vue';
  import IdTable from './component/IdTable.vue';
  import fileUp from '../component/fileUp.vue';
  import smallTable from '../component/smallTable.vue';
  import { DataItem, addModel, SmallModal } from './type/addDatas';
  import { message } from 'ant-design-vue';
  import { reactive, ref, onMounted } from 'vue';
  import type { Ref } from 'vue';
  import { searchList } from '@/api/test/api';
  import { getAllStandard, findSource, getPartStandard, changeStatus, changeAllStatus, deleteStandard } from '@/api/test/Standard';
  import { Status, Colors } from '@/pages/enumType/enum';
  import { standardsStatus } from './enums/enums';
  //查询所有数据
  let sources: Ref<string[]> = ref([]);
  // let statusData = ref('');
  // let typeData = ref('');
  // let nullData = ref('');
  console.log(Status['已停用'], '2222');
  let newData = ref<string>('');
  const dataSource: Ref<DataItem[]> = ref([]);
  dataSource.value = [
    {
      codesId: 'MGB0001',
      standardId: 'MGB0001',
      standardName: 'string',
      standardEnglish: 'string',
      standardMsg: 'string',
      standardStatus: 1,
      standardSource: 'string',
      standardIsNull: 1,
      standardDataType: 2,
      standardDefault: 'string',
      standardDataLength: 'string',
      standardDataAccuracy: 'string',
      standardDataMax: 'string',
      standardDataMin: 'string',
      standardIsDelete: 'string',
      modifyTime: 'string',
      addTime: 'string',
    },
    {
      codesId: 'MGB0001',
      standardId: 'MGB0001',
      standardName: 'string',
      standardEnglish: 'string',
      standardMsg: 'string',
      standardStatus: 3,
      standardSource: 'string',
      standardIsNull: 2,
      standardDataType: 1,
      standardDefault: 'string',
      standardDataLength: 'string',
      standardDataAccuracy: 'string',
      standardDataMax: 'string',
      standardDataMin: 'string',
      standardIsDelete: 'string',
      modifyTime: 'string',
      addTime: 'string',
    },
  ];

  onMounted(async () => {
    const resAll = await getAllStandard();
    dataSource.value = resAll.data;

    // 来源机构数据获取
    const resSource = await findSource();
    sources.value = resSource.data;
    // 处理数据
    sources.value = sources.value.map(item => item.standardSource);
    // console.log(sources.value[0].standardSource, '22222');
    if (newData.value == '') {
      newData.value = String(
        dataSource.value.map((item: DataItem) => {
          return item.standardName;
        }),
      );
    }
  });

  // dataSource.value.forEach((item: any) => {
  //   //状态转换
  //   if (item.standardStatus == 1) {
  //     statusData.value = '未发布';
  //     console.log('1');
  //     return item;
  //   } else if (item.standardStatus == 2) {
  //     statusData.value = '已发布';
  //     console.log('2');
  //     return item;
  //   } else if (item.standardStatus == 3) {
  //     item.statusData.value = '已停用';
  //     console.log('3');
  //     return item;
  //   }
  //   //类型转换
  //   if (item.standardDataType == 1) {
  //     typeData.value = 'String';
  //   } else if (item.standardDataType == 2) {
  //     typeData.value = 'Float';
  //   } else if (item.standardDataType == 3) {
  //     typeData.value = 'Int';
  //   } else if (item.standardDataType == 4) {
  //     typeData.value = 'Enum';
  //   }
  //   //是否可为空转换
  //   if (item.standardIsNull == 1) {
  //     nullData.value = '不可为空';
  //   } else if (item.standardIsNull == 2) {
  //     nullData.value = '可为空';
  //   }
  // });
  //input框开始
  // 下拉框数据
  const options = [
    { value: 1, label: '未发布' },
    { value: 2, label: '已发布' },
    { value: 3, label: '已停用' },
  ];
  let selectstandardSourceValue = ref<string>('请选择');
  let selectstandardStatusValue = ref<string>('请选择');
  let inputstandardIdValue = ref<string>('');
  let inputstandardNameValue = ref<string>('');
  let inputstandardEnglishValue = ref<string>('');
  const reset = async () => {
    selectstandardSourceValue.value = '请选择';
    selectstandardStatusValue.value = '请选择';
    inputstandardIdValue.value = '';
    inputstandardNameValue.value = '';
    inputstandardEnglishValue.value = '';
    const resAll = await getAllStandard();
    if (resAll.code == 100200) {
      message.success('重置成功');
    }
    dataSource.value = resAll.data;
  };

  //新增弹窗开始
  let datas = ref<Object>({});
  const addCodeTable = ref<boolean>(false);
  let codeDialogName = ref<boolean>(false);
  const dialogStatue = ref<string>('');
  // 展开新增弹窗
  const showModal = (dataSource: DataItem[]) => {
    // addCodeTable 是控制弹窗展示的变量
    addCodeTable.value = true;
    dialogStatue.value = 'add';
  };
  // 展开编辑弹窗
  const showEditModal = (record: string) => {
    addCodeTable.value = true;
    dialogStatue.value = 'edit';
    datas.value = record;
  };
  const handleEditSuccessed = (data: addModel) => {
    dataSource.value.forEach(item => {
      if (item.standardId == data.standardId) {
        item.standardName = data.standardName;
        item.standardMsg = data.standardMsg;
        item.standardEnglish = data.standardEnglish;
        item.standardSource = data.standardSource;
        item.standardIsNull = data.standardIsNull;
        item.standardDataType = data.standardDataType;
        item.standardDefault = data.standardDefault;
        item.standardDataLength = data.standardDataLength;
        item.standardDataAccuracy = data.standardDataAccuracy;
        item.standardDataMax = data.standardDataMax;
        item.standardDataMin = data.standardDataMin;
      }
    });
  };
  const showAddCodeDialog = (show: string) => {
    // 子组件向外触发父组件事件“关闭”新增码表弹窗
    if (show === 'false') {
      addCodeTable.value = false;
    } else {
      addCodeTable.value = true;
    }
  };

  // 表格选中框开始
  const activeClass1 = ref(true);
  const activeClass2 = ref(true);
  const arr: Ref<string[]> = ref([]);
  const arrPause: Ref<string[]> = ref([]); //停用数组
  const arrIssue: Ref<string[]> = ref([]); //发布数组
  const selectChangEtion = (selectedRowKeys: string[], selectedRows: DataItem[]) => {
    arr.value = selectedRowKeys;
    // console.log('mmmmm', arr.value);
    let pauseCount = 0;
    let IssueCount = 0;
    arrIssue.value = [];
    arrPause.value = [];
    activeClass1.value = true;
    activeClass2.value = true;
    // if (selectedRows.length >= 2) {
    selectedRows.forEach(item => {
      if (item.standardStatus != 2) {
        pauseCount += 1; //记下一个可以发布的
        arrIssue.value.push(item.standardId);
      } else {
        IssueCount += 1; // 记下一个可以停用的
        arrPause.value.push(item.standardId);
      }
    });
    if (pauseCount >= 1) {
      activeClass1.value = false; //发布按钮变为可用
    }
    if (IssueCount >= 1) {
      activeClass2.value = false; //停用按钮变为可用
    }
    // }
    console.log(arrIssue.value, '要发布');
    console.log(arrPause.value, '要停用');
    selectedRowKeys = [];
  };

  // 枚举范围弹窗开始
  const visibleSmallModal = ref(false);
  let smallModalId = ref<string>('');
  const tableSmallModal: Ref<SmallModal[]> = ref([]);
  const showEnumModal = async (codesNo: string) => {
    visibleSmallModal.value = true;
    // 查询人员性别码表
    smallModalId.value = codesNo;
    const ressearchList = await searchList({ codesNo });
    // tableSmallModal.value = ressearchList.data;
  };
  const handleChangeShowSmallModal = () => {
    visibleSmallModal.value = false;
  };
  //标准编号弹窗开始
  const dataTable = ref<Object>('');
  const visibleIdModal: Ref<boolean> = ref(false);
  let smallModalId1 = ref<string>('');
  const showSmallModal = (standardNo: string, record: Object) => {
    visibleIdModal.value = true;
    smallModalId1.value = standardNo;
    dataTable.value = record;
  };
  // 查询码表
  const ChangeShowId = (show: string) => {
    if (show == 'false') {
      visibleIdModal.value = false;
    }
  };

  //模板下载开始
  function downloadFile() {
    window.location.href = '/码表模板.docx';
  }
  //码表导入弹窗
  let visibleCodeIn: Ref<boolean> = ref(false);
  const handleClickCodeIn = () => {
    visibleCodeIn.value = true;
  };
  const ChangeShow1 = (show: string) => {
    if (show == 'false1') {
      visibleCodeIn.value = false;
    }
  };

  //批量发布和批量停用
  const allIssueAndPause = async (num: number, status: number) => {
    // 发布  num 是3    停用  num 是 2
    // 发布  status 是2    停用  status 是 3
    console.log(num, status);
    let arr6 = [];
    if (num == 3) {
      arr6 = arrIssue.value;
    } else {
      arr6 = arrPause.value;
    }
    // console.log(arrIssue.value, 'arrIssue');
    activeClass1.value = true; //发布按钮变为禁用
    activeClass2.value = true; //停用按钮变为禁用

    // 1：未发布，2：已发布，3：已停用
    let data = {
      standardId: arr6,
      standardStatus: num,
    };
    console.log(arr6, 'dada');
    arr6.forEach((i: string) => {
      dataSource.value.filter(item => {
        if (item.standardId == i) {
          item.standardStatus = status;
        }
      });
    });
    // 接口
    const reschangeAllStatus = await changeAllStatus(data);
    // console.log(reschangeAllStatus, 'dadadada');
    if (reschangeAllStatus.code == 100200) {
      if (num == 3) {
        message.success('批量发布成功');
      } else {
        message.success('批量停用成功');
      }
    }
    arr.value = [];
  };

  //删除
  const confirm1 = (standardId: string) => {
    dataSource.value = dataSource.value.filter(item => item.standardId !== standardId);
    message.success('删除成功！');
    // 接口
    deleteStandard({ standardId }).then((res: any) => {
      console.log(res);
    });
    arr.value = [];
  };

  //发布
  const confirm2 = (standardId: string) => {
    // let data = {
    //   standardId: arr.value,
    // };
    // console.log(data, '11---');
    // 接口
    dataSource.value.filter(item => {
      if (item.standardId == standardId) {
        item.standardStatus = 2;
      }
    });
    let standardStatus = 2;
    changeStatus({ standardId, standardStatus }).then((res: any) => {
      console.log(res);
    });
    arr.value = [];

    message.success('发布成功！');
  };

  //停用
  const confirm3 = (standardId: string) => {
    let data = {
      standardId: arr.value,
    };
    console.log(data, '---');
    // 接口
    dataSource.value.filter(item => {
      if (item.standardId == standardId) {
        item.standardStatus = 3;
      }
    });
    let standardStatus = 3;
    changeStatus({ standardId, standardStatus }).then((res: any) => {
      console.log(res);
    });
    arr.value = [];

    message.success('停用成功！');
  };

  // 查询接口开始
  const search = async () => {
    let data = {
      standardStatus: selectstandardStatusValue.value != '请选择' ? parseInt(selectstandardStatusValue.value) : '',
      standardSource: selectstandardSourceValue.value,
      standardEnglish: inputstandardEnglishValue.value,
      standardName: inputstandardNameValue.value,
      standardId: inputstandardIdValue.value,
    };
    // 判断模糊查询
    // let selectStatusValue = ;
    if (selectstandardStatusValue.value == '请选择') {
      delete data.standardStatus;
    }
    if (selectstandardSourceValue.value == '请选择') {
      delete data.standardSource;
    }
    if (inputstandardEnglishValue.value == '') {
      delete data.standardEnglish;
    }
    if (inputstandardNameValue.value == '') {
      delete data.standardName;
    }
    if (inputstandardIdValue.value == '') {
      delete data.standardId;
    }
    console.log(data);
    const res = await getPartStandard(data);
    if (res.code == 100200) {
      message.success('查询成功');
    }
    dataSource.value = res.data.records;
    console.log(res);
  };
  // 查询接口结束

  // 分页开始
  let pagination = {
    defaultPageSize: 5,
    showTotal: (total: number) => `共 ${total} 条`,
    showSizeChanger: true,
    showQuickJumper: true,
    position: ['bottomCenter'],
    pageSizeOptions: ['5', '10', '15', '20'],
    onShowSizeChange: (current: number, pageSize: number) => pageSize,
  };
  //分页结束
</script>
<style lang="less" scoped>
  .body-wrapper {
    position: absolute;
    margin-top: 40px;
    margin-left: 20px;
    width: 85%;

    .body-top {
      display: flex;
      margin-bottom: 40px;
      width: 90%;

      .body-top2 {
        position: absolute;
        display: flex;
        margin-top: 50px;

        .tip {
          position: relative;
          top: 20px;
          right: 6px;
          border: none;
          width: 30px;
          height: 30px;
          background-color: rgba(255, 255, 255, 0);

          img {
            position: absolute;
            top: 0;
            left: 0;
            width: 30px;
          }
        }
      }

      .select {
        display: flex;
        width: 200px;
        height: 40px;
        line-height: 40px;
        // align-items: center;
        .ant-select {
          margin-left: 5px;
        }

        .ant-input {
          margin-left: 5px;
          width: 120px;
          height: 32px;
        }
      }

      .ant-btn-primary {
        border: none;
        background-color: rgb(49, 149, 216) !important;
      }

      .activeClass {
        color: aliceblue;
        background-color: #3195d8 !important;
      }

      .ant-btn-primary:not(.ant-btn-primary:nth-child(7)) {
        margin-top: 25px;
      }

      .editable-cell:hover .editable-cell-icon {
        display: inline-block;
      }
    }

    .operate {
      margin: 3px;
      background-color: rgb(49, 149, 216) !important;
    }
  }

  .ant-btn {
    margin-right: 5px;
    border-radius: 5px;
  }

  #btn-top {
    margin-top: 0px;
  }

  /deep/ .ant-table {
    min-height: 60vh;
  }
</style>
